//
//  ZNWBUserCount.swift
//  ZNWeibo
//
//  Created by FunctionMaker on 2017/8/13.
//  Copyright © 2017年 FunctionMaker. All rights reserved.
//

import UIKit

class ZNWBUserCount: NSObject {
    
    private let accountFile: NSString = "userAccountInfo.json"
    
    //访问令牌开发者号有限时间为5年：每次登录重新计算，测试账号为3天：从第一次登录递减
    var access_token: String?
    
    //用户代号
    var uid: String?
    
    // 用户昵称
    var screen_name: String?
    
    // 用户头像
    var avatar_large: String?
    
    //token的时间限制
    var expires_in: TimeInterval = 0 {
        didSet {
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    
    var expiresDate: Date?
    
    override var description: String {
        return yy_modelDescription()
    }
    
    override init() {
        super.init()
        
        // 从磁盘中加载用户信息
        guard let path = accountFile.cz_appendDocumentDir(),
              let data = NSData(contentsOfFile: path),
        let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String: AnyObject]
        else {
            return
        }
        
        // 使用字典初始化用户对象
        // 用户登录与否的关键代码
        yy_modelSet(with: dict ?? [:])
        
        print("从沙盒加载用户信息\(self)")
        
        // 判断token是否过期
//        expiresDate = Date(timeInterval: -36000 * 2400, since: Date())
        if expiresDate?.compare(Date()) != .orderedDescending {
            print("token过期")
            access_token = nil
            uid = nil
            expiresDate = nil
            
            // 删除账户信息
            try? FileManager.default.removeItem(atPath: path)
        }
    }
    
    /// 保存账户信息在磁盘（沙盒）
    func saveToDisk() {
        // 1. 模型转字典
        var modelDict = (self.yy_modelToJSONObject() as? [String: AnyObject]) ?? [:]
        
        // 2. 删除expires_in
        modelDict.removeValue(forKey: "expires_in")
        
        // 3. 字典序列化 -> data
        guard let data = try? JSONSerialization.data(withJSONObject: modelDict, options: []),
              let filePath = accountFile.cz_appendDocumentDir()
        else {
            return;
        }
        
        // 4. 写入磁盘
        (data as NSData).write(toFile: filePath, atomically: true)
        
        print("用户信息写入磁盘成功:\(filePath)")
    }
}
